﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace org.alex.edss
{
    public class SessionPool
    {
        public int Length
        {
            get;
            set;
        }

        private SortedDictionary<int, Session> ActiveSession;

        private Queue<Session> UnActivePool;

        public SessionPool(int Len,int BufferLength)
        {
            try
            {
                Length = Len;
                ActiveSession = new SortedDictionary<int, Session>();
                UnActivePool = new Queue<Session>(Len);
                for (int i = 0; i < Len; i++)
                {
                    UnActivePool.Enqueue(new Session(BufferLength));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("init session pool error",ex);
            }
        }
        public Session GetSession(int Key)
        {
            try
            {
                lock (this)
                {
                    Session ses = UnActivePool.Dequeue();
                    ActiveSession.Add(Key, ses);
                    ses.Key = Key;
                    return ses;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("get session error", ex);
            }
        }
        public void ReleaseSession(int Key)
        {
            try
            {
                if (ActiveSession.ContainsKey(Key))
                {
                    lock (this)
                    {
                        Session Ses = ActiveSession[Key];
                        Ses.Reset();
                        UnActivePool.Enqueue(Ses);
                        ActiveSession.Remove(Key);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("release session error", ex);
            }
        }
    }
}
